<html>
<head><title>CS143 Project 1B SQL Query Page</title></head>
<body>
Type an SQL query in the following box:
<p>
<form method="POST">
<textarea name="query" cols="60" rows="8"></textarea>
<input type="submit" value="Submit" />
</form>
</p>
<?php
    // POST used instead of GET to avoid the 100 character limit
    $query = $_POST["query"];
    
    // If a query was given, process it
    if ($query){
        // If the query will not insert, update, or delete anything, proceed, else return error
        if ((preg_match("#insert#i", $query, $insert_check) === 0) &&
            (preg_match("#update#i", $query, $update_check) === 0) &&
            (preg_match("#delete#i", $query, $delete_check) === 0)){
            
            // Establish connection and select database
            $db_connection = mysql_connect("localhost", "cs143", "");
            mysql_select_db("CS143", $db_connection);
            
            // Since users are formatting the entire query themeselves mysql_real_escape_string only causes errors
            // Issue query
            $rs = mysql_query($query, $db_connection);
            
            // If there are results, print them, otherwise return error
            if ($rs != False){
                // Start results table
                echo "<table border=1 cellspacing=1 cellpadding=2>";
                
                // The first row lists the field names as Table.field
                echo "<tr align=center>";
                for($i = 0; $i < mysql_num_fields($rs); $i++){
                    $info = mysql_fetch_field($rs, $i);
                    echo '<td><b>' . $info->table . '.' . $info->name . '</b></td>';
                }
                echo "</tr>";
                
                while($row = mysql_fetch_row($rs)) {
                    // Start row
                    echo "<tr align=center>";
                    for ($j = 0; $j < mysql_num_fields($rs); $j++){
                        // Print element
                        $element = $row[$j];
                        
                        // If the element is null, print N/A instead
                        if ($element === NULL){
                            $element = "N/A";
                        }
                        
                        echo "<td>$element</td>";
                    }
                    // End row
                    echo "</tr>";
                }
                // End results table
                echo "</table?";
            }
            else{
                echo 'Query failed: ' . mysql_error();
            }
            
            //Close connection
            mysql_close($db_connection);
        }
        else{
            echo "Invalid query -- will modify database.";
        }
    }
?>
</body>
</html>
